package com.application.Activity;

import it.unipr.ce.dsg.s2p.sip.Address;

import java.util.ArrayList;

import ReadWriteXML.CMember;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;
import com.application.DTO.AccountDTO;
import com.application.DTO.RoleDTO;
import com.application.Network.NetworkLayer;
import com.application.Network.Protocol;
import com.application.PhanQuyen.Quyen;
import com.application.QuickAction.ActionItem;
import com.application.QuickAction.QuickAction;

import com.application.Tree.BoardView;
import com.application.Tree.BoardViewTN;
import com.application.Tree.TextNode;
import com.application.Tree.TreeNode;

//import com.application.Activity.R;

public class frmTreeNodeActivity extends Activity implements View.OnClickListener {
	/** Called when the activity is first created. */
	public static int ON_EXIT_APP = 1111;
	public static int CODE_KICK = 101;
	public static int CODE_STOP_TALK = 301;
	public static String IP_RESULT = "IP_RESULT";
	public static Address ipBeingStopTalk;
	int timeStopTalk;
	public static int kickVoteResult;
	public static Address ipBeingKick;
	public static int timeVoteKick;
	ArrayList<CMember> memberList;
	public static ArrayList<Integer> yesVote;
	public static ArrayList<Integer> noVote;
	public static Runnable dislayKickMember;
	public static Runnable dislayKickedMessage;
	public static Runnable raShowMessage;
	public static String message;
	public ArrayList<Quyen> quyen = null;
	public static AccountDTO account = null;
	public EditText listChat;
	public EditText txtContent;
	public static Context baseContext;
	public static Handler handler = new Handler();

	public static Runnable raSignout;
	public static Runnable raStopSession;
	public static Runnable raShowDanhGia;
	public static Runnable raShowBieuQuyet;
	static String loi = "";
	String ip = "";

	public static int idindex = 0;
	public static Address Address;
	public static String _title = "";
	// ============SUY NGHI LAI Co NEN DE O DAY
	// KO?????????????====================

	public static Runnable raAddnode = null;
	public static Runnable raAddnodetext = null;
	public static Runnable raUpdateTextNode = null;
	public static Runnable raUpdateNodeText = null;
	public static Runnable raDeleteNode = null;
	public static Runnable raDeleteNodeText = null;
	public static Runnable raResetTree = null;
	LinearLayout layout;
	String value = "";
	public static BoardView board = null;
	private BoardViewTN boardTN;
	LayoutInflater layoutInflater;
	FrameLayout frmLayout;
	Button btnSwitch, btnSaveTree, btnDeleteAll;
	public static long idNode;
	public static String textUpdate = "";
	public static long id = 0;
	public static TreeNode nodeAdd;
	public static TextNode textnodeAdd;
	public static boolean isActive = false;
	public static int flag;
	private boolean sw = false;
	Button btnZoomOut, btnZoomIn;
	float scale = 1.0f;
	public static long version;
	public static int lb;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_tree_node);
		Log.d("Phu", "frmTreeNodeActivity onCreate");
		isActive = true;
		board = (BoardView) findViewById(R.id.boardID);
		boardTN = (BoardViewTN) findViewById(R.id.boardtextID);
		boardTN.setVisibility(View.GONE);
		// board.writeXML(BoardView.treePath);

		board.setVisibility(View.VISIBLE);
		board.readXml(BoardView.treePath);
		Log.d("Phu", "frmTreeNodeActivity-... đọc file vao nodes :.." + board.getTree().getSumChildren());
		btnZoomIn = (Button) findViewById(R.id.btnZoomIn);
		btnZoomOut = (Button) findViewById(R.id.btnZoomOut);
		btnZoomIn.setOnClickListener(this);
		btnZoomOut.setOnClickListener(this);

		board.isActive = true;
		// boardTN.isActive = false;
		raAddnode = new Runnable() {
			@Override
			public void run() {
				Log.d("Phu", "frmTreeNodeActivity-raAddnode....board.isActive= " + board.isActive);
				if (board.isActive) {
					Log.d("Phu", "da vao raAddnode roi" + (board == null));
					board.addNode(idNode, nodeAdd, BoardView.treePath);
					board.autoArrange();
				}

			}
		};
		raAddnodetext = new Runnable() {
			@Override
			public void run() {
				if (boardTN.isActive) {
					Log.d("Phu", "frmTreeNodeActivity-raAddnodetext ,kakaka" + (boardTN == null));
					boardTN.addNode(idNode, textnodeAdd, BoardViewTN.treePath);
				}
				boardTN.autoArrange();
			}
		};
		raUpdateTextNode = new Runnable() {
			@Override
			public void run() {
				if (board.isActive) {
					board.updateText(nodeAdd, BoardView.treePath);

				}
			}
		};
		raUpdateNodeText = new Runnable() {
			@Override
			public void run() {
				if (boardTN.isActive)
					boardTN.updateText(textnodeAdd, BoardViewTN.treePath);
			}
		};
		raDeleteNode = new Runnable() {

			@Override
			public void run() {
				Log.d("An", "frmTreeNodeActivity-raDeleteNode... board.isActive= " + board.isActive);
				if (board.isActive) {
					Log.d("An", "frmTreeNodeActivity-raDeleteNode... id= " + nodeAdd.getId());
					board.removeNodeById(nodeAdd, BoardView.treePath);
				}
			}
		};
		raDeleteNodeText = new Runnable() {

			@Override
			public void run() {
				if (boardTN.isActive) {
					Log.d("An", "frmTreeNodeActivity-raDeleteNode Text: idNode= " + nodeAdd.getId());
					boardTN.removeNodeById(textnodeAdd, BoardViewTN.treePath, BoardViewTN.DeletedNodesPath);
				}
			}
		};
		raResetTree = new Runnable() {

			@Override
			public void run() {
				// resetTree();
			}
		};
		btnSwitch = (Button) findViewById(R.id.btnSwitch);
		btnSwitch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (boardTN.isActive) {

					// Ghi cây bên text tree xuống file
					boardTN.isActive = false;
					boardTN.setVisibility(View.GONE);
					boardTN.writeXML(BoardView.treePath);

					// Đọc tree node từ file lên
					board.readXml(BoardView.treePath);
					board.autoArrange();
					board.setVisibility(View.VISIBLE);
					board.isActive = true;
					board.moveCenter();
					sw = false;
				} else {
					// Ghi cây bên tree node xuống file
					board.writeXML(BoardView.treePath);
					board.setVisibility(View.GONE);
					board.isActive = false;

					// Đọc text tree từ file lên
					boardTN.isActive = true;
					boardTN.readXml(BoardView.treePath);
					// boardTN.au
					boardTN.setVisibility(View.VISIBLE);
					boardTN.settree(3, 2);
					sw = true;
				}
			}
		});

		// ====+TRUC

		// raShowMessage=new Runnable() {
		//
		// @Override
		// public void run() {
		// // TODO Auto-generated method stub
		// ShowOnTree(message);
		// }
		// };
		// END TRUC========
		// ===an=====
		raSignout = new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Log.d("Phu", "vao 'raSignout'");
				showMessageSignOut(loi);
			}
		};
		// Runalbe raShowDanhGia
		raShowDanhGia = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// Hien thong bao yeu cau nguoi khac Danh gia
				displayNotificationDanhGia();
			}
		};
		raShowBieuQuyet = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// hien thong bao yeu cau Bieu Quyet
				displayNotificationBieuQuyet();
			}
		};
		// ====end an
	}

	public void showAlert() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		final EditText input = new EditText(this);
		alert.setTitle("Nhập nội dung!");
		alert.setView(input);
		alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				value = input.getText().toString();
			}
		});

		alert.show();
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.btnZoomIn:
			scale += 0.2;
			board.zoom(scale);
			break;
		case R.id.btnZoomOut:
			// scale-=0.2;
			// if(scale<=0.2)
			// scale=0.2f;
			// board.zoom(scale);
			NetworkController.sendVersionTree("192.168.1.88:" + Protocol.PORT, board.treeversion());
			break;
		default:
			break;
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		ActivityController.setPeerActivity(this);
		Log.d("Phu", "frmTreeNodeActivity onResume");
		board.readXml(BoardView.treePath);
		board.autoArrange();
		board.isActive = true;
	}

	@Override
	public void onStop() {
		super.onStop();
		isActive = false;
		board.writeXML(BoardView.treePath);
		Log.d("Phu", "frmTreeNodeActivity onStop");
	}

	@Override
	public void onPause() {
		super.onPause();
		isActive = false;

		// isActive=true;
		board.writeXML(BoardView.treePath);
		board.isActive = false;

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d("Phu", "frmTreeNodeActivity onDestroy");
	}

	@Override
	public void onStart() {
		super.onStart();
		ActivityController.addActivityToArray(this);
		board.isActive = true;
		isActive = true;
		if (board != null) {
			try {

				board.readXml(BoardView.treePath);
				board.autoArrange();
			} catch (Exception e) {
				Log.d("Phu", "ko doc duoc tree:" + e);
			}
		}
		if (NetworkController._peer == null) {
			String s = "";
			AccountDTO account = new AccountDTO();
			account.set_Username("quocphu");
			ArrayList<RoleDTO> roleList = ReadWriteFileController.readRole(null, ReadWriteFileController.MY_ROLE_PATH);

			for (RoleDTO role : roleList) {
				account.addRole(role);
				Log.i("Phu", "Role: " + role.getName());
			}
			NetworkController.init("MES", Protocol.PORT, account);

		}

		this.setTitle(NetworkController._peer.getAddressPeer());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		// menu.add(Menu.NONE, NOTEPAD, Menu.NONE, "Note")
		// .setIcon(R.drawable.img_clear)
		// .setAlphabeticShortcut('e');
		// menu.add(Menu.NONE, INTERACTION, Menu.NONE, "Cộng tác")
		// .setIcon(R.drawable.img_cauhoi)
		// .setAlphabeticShortcut('f');
		// menu.add(Menu.NONE, SETTING, Menu.NONE, "Tuỳ chỉnh")
		// .setIcon(R.drawable.img_chat)
		// .setAlphabeticShortcut('g');
		// return(super.onCreateOptionsMenu(menu));
		new MenuInflater(getApplication()).inflate(R.menu.omnu_thao_luan, menu);
		return (super.onCreateOptionsMenu(menu));
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d("Phu", " vao ham onActivityResult tree");
		if (resultCode == CODE_KICK) {
			Log.d("Phu", " CODE_KICK");
			String ipKick = data.getStringExtra(IP_RESULT);
			if (ipKick != null) {
				// userNameKick = data.getStringExtra(USERNAME_BEING_KICK);
				ShowSetTimeVoteKick(ipKick);

			}
		}
		if (resultCode == CODE_STOP_TALK) {
			Log.d("Phu", " CODE_STOP_TALK");
			String ipStop = data.getStringExtra(IP_RESULT);
			if (ipStop != null) {
				// userNameStop = data.getStringExtra(USERNAME_STOP_TALK);
				ShowSetTimeStopTalking(ipStop);
			}
		}
		if (resultCode == ON_EXIT_APP) {
			finish();
		}
	}

	// ============THINKING=====================

	public void ShowSetTimeVoteKick(final String IP) {

		Log.d("Phu", " vao ShowSetTimeVoteKick");
		Log.d("Phu", "ip kick" + IP);
		Log.d("Phu", "My ip " + NetworkController._peer.getAddressPeer());
		String s[] = IP.split(":");

		String ipBeKick = s[1] + ":" + s[2];
		Log.d("Phu", "ip be kick " + ipBeKick);
		if (NetworkController._peer.getAddressPeer().equals(ipBeKick)) {
			NetworkController.ShowMessageNoticeTAB("Bạn không thể làm điều này!");
		} else {
			final EditText txtTime = new EditText(this);
			txtTime.setSingleLine();
			txtTime.setInputType(2);
			AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Chọn thời gian biểu quyết")
					.setMessage("Thời gian được tính bằng giây.").setView(txtTime)
					.setPositiveButton("OK", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							String StrTime = txtTime.getText().toString();
							int time = Integer.parseInt(StrTime);
							timeVoteKick = time;
							yesVote = new ArrayList<Integer>();
							noVote = new ArrayList<Integer>();
							ipBeingKick = new Address(IP);
							// memberList =
							// ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
							// for (CMember member : memberList) {
							// NetworkController.SendVoteKickMember(new
							// Address(member.get_ip()), ipBeingKick, time);
							// }
							NetworkController.SendVoteKickMemberGroup("TRUC", ipBeingKick, time);
							Log.d("Phu", "Da gui xong kick");
							// dem thoi gian
							long kickTime = timeVoteKick * 1000;

							CountDownTimer timer = new CountDownTimer(kickTime, 1000) {
								@Override
								public void onTick(long millisUntilFinished) {

								}

								@Override
								public void onFinish() {
									// Toast.makeText(getBaseContext(),
									// "het gio kick",
									// Toast.LENGTH_SHORT).show();
									Log.w("Phu", "yes size=" + yesVote.size());
									Log.w("Phu", "no size=" + noVote.size());
									kickVoteResult = 0;
									if (yesVote.size() != 0 || noVote.size() != 0) {

										if (yesVote.size() >= noVote.size()) {
											kickVoteResult = 1;
										}
										memberList = ReadWriteFileController
												.readMember(ReadWriteFileController.MEMBER_PATH);
										for (CMember member : memberList) {
											Log.d("Phu", "gui result toi " + member.get_ip());
											NetworkController.SendResultVoteKickMember(new Address(member.get_ip()),
													kickVoteResult, ipBeingKick);
										}
									} else {
										// NetworkController.ShowMessageNotice("Không có ai tham gia biểu quyết.");
										NetworkController.ShowMessageNoticeTAB("Không có ai tham gia biểu quyết.");
										memberList = ReadWriteFileController
												.readMember(ReadWriteFileController.MEMBER_PATH);
										for (CMember member : memberList) {
											Log.d("Phu", "gui result toi " + member.get_ip());
											NetworkController.SendResultVoteKickMember(new Address(ipBeingKick),
													kickVoteResult, ipBeingKick);
										}
									}
								}
							}.start();
						}
					}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub

						}
					}).create();
			dlg.show();
		}
	}

	public void ShowSetTimeStopTalking(final String ipStop) {
		final EditText txtTimeTalk = new EditText(this);
		txtTimeTalk.setSingleLine();
		txtTimeTalk.setInputType(2);
		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Chọn thời gian buộc ngừng thảo luận")
				.setMessage("Thời gian được tính bằng giây.").setView(txtTimeTalk)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						String StrTime = txtTimeTalk.getText().toString();
						int time = Integer.parseInt(StrTime);
						timeStopTalk = time;
						ipBeingStopTalk = new Address(ipStop);
						NetworkController.GuiYeuCauNgungThaoLuan(ipBeingStopTalk, time);
						Log.d("Phu", "vao onclick ngung noi");
						long timeLong = timeStopTalk * 1000;
						Toast.makeText(getBaseContext(), timeLong + "", 1).show();
						CountDownTimer timer = new CountDownTimer(timeLong, 1000) {

							@Override
							public void onTick(long millisUntilFinished) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onFinish() {
								// TODO Auto-generated method stub

								NetworkController.GuiChoPhepThaoLuan(ipBeingStopTalk);
							}
						}.start();
					}

				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

					}
				}).create();
		dlg.show();
	}

	// public void ShowOnTree(String message) {
	//
	// AlertDialog dlg = new
	// AlertDialog.Builder(this).setTitle("Thông báo").setMessage(message)
	// .setPositiveButton("OK", new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	// // TODO Auto-generated method stub
	// }
	// }).create();
	// dlg.show();
	// }
	// //=======END THINKING====================
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d("PEERDROID", " vao on key down");
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setIcon(R.drawable.img_dialog);
			builder.setMessage("Bạn có chắc muốn rời khỏi nhóm hiện tại ?").setCancelable(false)
					.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {

							Thoat();
						}
					}).setNegativeButton("No", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
			AlertDialog alert = builder.create();
			alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255)));
			alert.show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		// switch (item.getItemId()) {
		// case NOTEPAD:
		// startActivity(new Intent(this, FrmNote.class));
		// return(true);
		// case INTERACTION:
		// startActivity(new Intent(this, FrmInteraction.class));
		// return(true);
		// case SETTING:
		// startActivity(new Intent(this, PrefSetting.class));
		// return(true);
		// }

		// return super.onOptionsItemSelected(item);
		int id = item.getItemId();
		switch (id) {
		case R.id.mnuDanhSachThanhVien:
			Intent iDanhSachThanhVien = new Intent(getBaseContext(), frmDanhSachThanhVienActivity.class);
			startActivityForResult(iDanhSachThanhVien, CODE_KICK);
			break;
		case R.id.mnuChiaSeTaiLieu:
			Toast.makeText(getBaseContext(), "Chia sẻ tài liệu", 1).show();
			break;
		case R.id.mnuVaoTroCuaToi:
			Intent iVaiTro = new Intent(getBaseContext(), frmVaiTroCuaToiActivity.class);
			startActivity(iVaiTro);
			break;
		case R.id.mnuQuyenCuaToi:
			Intent iQuyen = new Intent(getBaseContext(), frmQuyenCuaToi.class);
			startActivity(iQuyen);
			break;
		case R.id.mnuBieuQuyet:
			// Intent iBieuQuyet = new Intent(getBaseContext(),
			// frmBieuQuyetActivity.class);
			// startActivity(iBieuQuyet);
			View v = new View(getApplicationContext());

			BieuQuyet(v);
			break;
		case R.id.mnuDanhGia:
			// Intent iDanhGia = new Intent(getBaseContext(),
			// frmDanhGiaActivity.class);
			// startActivity(iDanhGia);
			showDanhGiaQuestion();
			// DanhGia();
			break;
		case R.id.mnuThoat:
			Thoat();
			break;
		default:
			break;
		}
		return true;
	}

	public void Thoat() {
		ArrayList<CMember> cmem = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
		for (int i = 0; i < cmem.size(); i++) {
			String name = String.valueOf(NetworkController._peer.getAccount().get_Username());
			Log.d("PEERDROID", "fullname: " + name);
			NetworkController.sendGroupSignOut(cmem.get(i).get_ip(), name);
		}
		NetworkController._peer.getAccount().setInGroup(false);
		// ghi xuống file Log
		String text = "Đã rời khỏi nhóm..";
		ReadWriteFileController.checkRuleWriteToLogFile(text);
		NetworkLayer.amountMember=0;
		finish();
	}

	public void DanhGia() {

		Quyen quyen = NetworkController._peer.getAccount().getRuleById(19);
		Log.d("PEERDROID", "Quyen send Đánh giá = " + quyen.getSend());
		if (quyen != null && quyen.getSend()) {
			ArrayList<CMember> cmem = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
			for (int i = 0; i < cmem.size(); i++) {
				Log.d("PEERDROID", "IP memberlist: " + String.valueOf(cmem.get(i).get_ip()));
				NetworkController.sendGroupDanhGia(cmem.get(i).get_ip());
				// NetworkController.sendGroupDanhGia("192.168.1.99:" + port);
			}

			// ghi xuống file Log
			String text = "Gởi yêu cầu Đánh giá..";
			ReadWriteFileController.checkRuleWriteToLogFile(text);
		} else {
			Show(Protocol.NON_RULE_MESSAGE);
		}
	}

	public void Show(String message) {

		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Thông báo").setMessage(message)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
					}
				}).create();
		dlg.show();
	}

	public void BieuQuyet(View v) {
		// Các khai báo QuickAction
		// vote100accept action item
		ActionItem vote100accept = new ActionItem();

		vote100accept.setTitle("100% Accept");
		vote100accept.setIcon(getResources().getDrawable(R.drawable.ic_add));

		// vote75accept action item
		ActionItem vote75accept = new ActionItem();

		vote75accept.setTitle("75% Accept");
		vote75accept.setIcon(getResources().getDrawable(R.drawable.ic_accept));

		// vote50accept action item
		ActionItem vote50accept = new ActionItem();

		vote50accept.setTitle("50% Accept");
		vote50accept.setIcon(getResources().getDrawable(R.drawable.ic_up));

		final QuickAction mQuickAction = new QuickAction(this);
		// add QuickAction
		mQuickAction.addActionItem(vote100accept);
		mQuickAction.addActionItem(vote75accept);
		mQuickAction.addActionItem(vote50accept);

		// setup the action item click listener
		mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
			@Override
			public void onItemClick(int pos) {
				if (pos == 0) { // Add item selected
					showDialogQuickAction(1);
				} else if (pos == 1) { // Accept item selected
					showDialogQuickAction(2);
				} else if (pos == 2) { // Upload item selected
					showDialogQuickAction(3);
				}
			}
		});
		Quyen quyen = NetworkController._peer.getAccount().getRuleById(18);
		Log.d("PEERDROID", "Quyen send = " + quyen.getSend());
		if (quyen != null && quyen.getSend()) {
			mQuickAction.show(v);

			mQuickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER);
		} else {
			Log.d("PEERDROID", "ko co quyen send bieu quyet ");
			Show(Protocol.NON_RULE_MESSAGE);
		}
	}

	// Hàm Show Dialog khi click chọn QuickAction
	public void showDialogQuickAction(final int index) {
		final EditText txtTitle = new EditText(this);
		txtTitle.setInputType(1);
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("Yêu Cầu Biểu Quyết").setMessage("Nhập vào vấn đề muốn biểu quyết").setView(txtTitle)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						String strTitle = txtTitle.getText().toString();
						ArrayList<CMember> cmem = ReadWriteFileController
								.readMember(ReadWriteFileController.MEMBER_PATH);
						for (int i = 0; i < cmem.size(); i++) {
							NetworkController.sendGroupBieuQuyet(cmem.get(i).get_ip(), index, strTitle);
						}
						// Ghi xuống file Log
						String text = "Đã gởi yêu cầu Biểu Quyết..";
						// checkIsThanhLapNhom(text);
						ReadWriteFileController.checkRuleWriteToLogFile(text);
					}
				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				}).create();
		dialog.show();
	}

	public static void showSignOut(String name) {
		loi = name;
		Log.d("PEERDROID", "name sign out: " + loi);
		handler.post(raSignout);

	}

	public void showDanhGiaQuestion() {
		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Thông báo")
				.setMessage("Bạn thật sự muốn gửi yêu cầu đánh giá?")
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						DanhGia();
					}
				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				}).create();
		dlg.show();
	}

	public void showMessageSignOut(String name) {
		Log.d("PEERDROID", "vao day");
		Toast.makeText(this, name + " da roi nhom", Toast.LENGTH_SHORT).show();
	}

	public void displayNotificationDanhGia() {
		Intent intent = new Intent(this, frmDanhGiaActivity.class);
		Bundle ex = new Bundle();
		ex.putInt("ID", 2);
		ex.putString("SENDER", String.valueOf(Address));
		intent.putExtras(ex);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
		NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification notif = new Notification(R.drawable.ic_launcher, "Co yeu cau Danh gia", System.currentTimeMillis());
		notif.setLatestEventInfo(this, "Danh gia ", "Vao de", pendingIntent);

		notiManager.notify(2, notif);
		Log.d("PEERDROID", "het show notifi danh gia");
	}

	public void displayNotificationBieuQuyet() {
		Intent intent = new Intent(this, frmBieuQuyetActivity.class);
		Bundle ex = new Bundle();
		ex.putInt("ID", 3);
		ex.putInt("INDEX", idindex);
		ex.putString("SENDER", String.valueOf(Address));
		ex.putString("TITLE", _title);
		intent.putExtras(ex);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
		NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification notif = new Notification(R.drawable.ic_launcher, "Co yeu cau Bieu Quyet",
				System.currentTimeMillis());
		notif.setLatestEventInfo(this, "Bieu quyet ", "Vao de", pendingIntent);

		notiManager.notify(3, notif);
		Log.d("PEERDROID", "het show notifi bieu quyet");
	}

	public static void showNotificationBieuQuyet(int index, Address sender, String title) {
		Log.d("PEERDROID", " da vao shownotifi......");
		idindex = index;
		Address = sender;
		_title = title;
		Log.d("PEERDROID", "vao frm truc" + String.valueOf(index) + String.valueOf(sender));
		handler.post(raShowBieuQuyet);
	}

	public static void showRequestDanhGia(Address sender) {
		Log.d("PEERDROID", " da vao shownotifi......");
		Address = sender;
		Log.d("PEERDROID", "vao frm truc" + String.valueOf(sender));
		handler.post(raShowDanhGia);
	}
}